//
//  HLGlobalFunction.swift
//  SwiftPods
//
//  Created by hulinhu on 2018/1/18.
//  Copyright © 2018年 hulinhu. All rights reserved.

//   全局方法

import Foundation
import RxSwift
import Reachability

// 网络延时xS
func delayToMainThread(_ delay:Double, closure:@escaping ()->()) {
    DispatchQueue.main.asyncAfter (
        deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}

// 路径输出
//let logger = Logger(destination: logPath())
func logPath() -> URL {
    let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
    return docs.appendingPathComponent("logger.txt")
}

// MARK: - 网络判断
private let reachabilityManager = ReachabilityManager ()
func connectedToInternetOrStubbing() -> Observable<Bool> {
    return reachabilityManager?.reach ?? Observable.just(false)
}

private class ReachabilityManager {
    private let reachability: Reachability
    let _reach = ReplaySubject<Bool>.create(bufferSize: 1)
    var reach: Observable<Bool> {
        return _reach.asObservable()
    }
    init?() {
        guard let r = Reachability() else {
            return nil
        }
        self.reachability = r
        do {
            try self.reachability.startNotifier()
        } catch {
            return nil
        }
        
        self._reach.onNext(self.reachability.connection != .none)
        self.reachability.whenReachable = { _ in
            DispatchQueue.main.async { self._reach.onNext(true) }
        }
        self.reachability.whenUnreachable = { _ in
            DispatchQueue.main.async { self._reach.onNext(false) }
        }
    }
    
    deinit {
        reachability.stopNotifier()
    }
}
